package com.wdt.data.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wdt.data.model.*;
import com.wdt.data.service.*;
import com.wdt.data.util.*;
import com.wdt.data.util.redis.RedisUtils;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sun.security.provider.MD5;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.regex.Pattern;

import static com.wdt.data.util.HttpClientUtil.postMap;
import static com.wdt.data.util.HttpUtil.getParm;
import static com.wdt.data.util.StrUtil.getRandomString;
import static com.wdt.data.util.TokenProccessor.getToken;

@RestController
@RequestMapping("/Api")
public class ReceiveDataApi {
    private Logger logger = LoggerFactory.getLogger(ReceiveDataApi.class);

    @Autowired
    private IDatBoilerdataService boilerdataService;
    @Autowired
    private IDatBoilerdataHistoryService boilerdataHistoryService;
    @Autowired
    private IDatCrewDataService crewDataService;
    @Autowired
    private IDatCrewDataHistoryService crewDataHistoryService;
    @Autowired
    private IDatHeatstationDataService heatstationDataService;
    @Autowired
    private IDatHeatstationDataHistoryService heatstationDataHistoryService;
    @Autowired
    private IDatHeatSourceOutletDataService heatSourceOutletDataService;
    @Autowired
    private IDatHeatSourceOutletDataHistoryService heatSourceOutletDataHistoryService;
    @Autowired
    private IDatHouseHoldDataService houseHoldDataService;
    @Autowired
    private IDatHouseHoldDataHistoryService houseHoldDataHistoryService;
    @Autowired
    IDatPublicBuildingDataService publicBuildingDataService;
    @Autowired
    IDatPublicBuildingDataHistoryService publicBuildingDataHistoryService;
    @Autowired
    IDatResidentialBuildingDataService residentialBuildingDataService;
    @Autowired
    IDatResidentialBuildingDataHistoryService residentialBuildingDataHistoryService;
    @Autowired
    IBasBoilerService boilerService;
    @Autowired
    IBasCrewService crewService;
    @Autowired
    IBasHeatstationService heatstationService;
    @Autowired
    IBasHeatsourceExitService basHeatsourceExitService;
    @Autowired
    IBasHouseholdService householdService;
    @Autowired
    IBasBuildingService basBuildingService;
    @Autowired
    IHouseholdPaymentService paymentService;
    @Autowired
    IHouseholdRefundService refundService;
    @Autowired
    IComplainInfoService complainInfoService;
    @Autowired
    IResultInfoService resultInfoService;
    @Autowired
    IGatherTemporaryService gatherTemporaryService;
    @Autowired
    IHeatingExceptionInfoService heatingExceptionInfoService;
    @Autowired
    IMapPolylinevalueService mapPolylinevalueService;
    @Autowired
    IBasHeatcompanyService heatcompanyServicel;
    @Autowired
    IDatRoomtempService roomtempService;
    @Autowired
    IDatRoomtempHistoryService datRoomtempHistoryService;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    ICompanyTokenService companyTokenService;
    @Autowired IBasCommunityService communityService;


    @RequestMapping(value = {"/get_token"}, method = {RequestMethod.POST})
    public R getAccessToken(HttpServletRequest request, @RequestBody String json) {
        if (StringUtils.isEmpty(json)) {
            return R.error("json字符串为空");
        }
        try {
            Map map = JsonUtil.fromJson(json, Map.class);
            if (StringUtils.isEmpty(map.get("requestId"))) {
                return R.ok("", "4", "requestId为空");
            }
            String requestId = map.get("requestId").toString();
            if (StringUtils.isEmpty(map.get("heatCompanyId"))) {
                return R.ok(requestId, "", "4", "heatCompanyId为空");
            }

            String heatCompanyId = map.get("heatCompanyId").toString();

            if (StringUtils.isEmpty(map.get("appId")) || StringUtils.isEmpty(map.get("appSecert"))) {
                return R.ok(requestId, heatCompanyId, "4", "appId或appSecert不可为空");
            }
            QueryWrapper<BasHeatcompany> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code", heatCompanyId);
            BasHeatcompany basHeatcompany = heatcompanyServicel.getOne(queryWrapper);
            if (basHeatcompany == null) {
                return R.ok(requestId, heatCompanyId, "4", "供热企业代码不正确");
            }

            String appId = map.get("appId").toString();
            String appSecert = map.get("appSecert").toString();
            QueryWrapper<CompanyToken> tokenQueryWrapper = new QueryWrapper<>();
            tokenQueryWrapper.eq("app_id", appId).eq("app_secret", appSecert);
            CompanyToken companyToken = companyTokenService.getOne(tokenQueryWrapper);
            if (companyToken == null) {
                return R.ok(requestId, heatCompanyId, "4", "appId或appSecert错误,请检查后再试");
            }
            if (!companyToken.getCompanyCode().equals(heatCompanyId)) {
                return R.ok(requestId, heatCompanyId, "4", "公司编码不匹配,请检查后再试");
            }
            String token = getToken(appId, appSecert);
            redisUtils.set(token, heatCompanyId, 1200l);
            Map tokenMap = new HashMap();
            tokenMap.put("token", token);
            tokenMap.put("expireTime", "20分钟");//超时时间20分钟
            return R.ok(tokenMap);
        } catch (Exception e) {
            return R.error("json格式有误");
        }
    }

    /**
     * 上传泵实时数据
     *
     * @param request
     * @return
     */

    //("上传泵实时数据 boilerCode  泵code  其他为运行数据  详情见接口说明")
    @RequestMapping(value = {"/boiler_data"}, method = {RequestMethod.POST})
    public R receiveBoilerData(HttpServletRequest request, @RequestBody String json) {
        R r = getParm(request, json);
        try {
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<DatBoilerdata> boilerdataList = new ArrayList<>();
            List<DatBoilerdataHistory> boilerdataHistoryList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    one.put("boilderCode", one.get("boilerId"));
                    if (StringUtils.isEmpty(one.get("boilerId")) || StringUtils.isEmpty(one.get("getTime")) || StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "运行数据必填项缺失");
                    }
                    QueryWrapper<BasBoiler> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code", one.get("boilerId"));
                    if (boilerService.getOne(queryWrapper) == null) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "boilerId错误，无对应锅炉数据");
                    }
                    String str = JsonUtil.toJson(one);
                    DatBoilerdata boilerdata = JsonUtil.fromJson(str, DatBoilerdata.class);
                    DatBoilerdataHistory boilerdataHistory = JsonUtil.fromJson(str, DatBoilerdataHistory.class);
                    boilerdata.setUpdateBy(-5);
                    boilerdataHistory.setUpdateBy(-5);
                    boilerdataList.add(boilerdata);
                    boilerdataHistoryList.add(boilerdataHistory);
                }
            }
            boilerdataService.saveOrUpdateBatch(boilerdataList);
            boilerdataHistoryService.saveBatch(boilerdataHistoryList);
            r.remove("data");
            return R.ok(r);
        } catch (Exception e) {
            logger.error("receiveBoilerDataException", e);
            return R.ok(e.getMessage());
        }
    }

    //("上传机组实时数据 参数为 【crewCode(机组编号)，instantaneousFlow(二次瞬时流量)，cumulativeHeat(二次累计热量),supplyTemp(二次供水温度),backTemp(二次回水温度),supplyPre(二次供压)，backPre（二次回压），getTime（数据时间）】 以上参数转为json 以data为参数名")
    @RequestMapping(value = {"/crew_data"}, method = {RequestMethod.POST, RequestMethod.GET})
    public R receiveCrewData(HttpServletRequest request, @RequestBody String json) {
        try {
            R r = getParm(request, json);
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<DatCrewData> crewDataList = new ArrayList<>();
            List<DatCrewDataHistory> crewDataHistoryList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    one.put("crewCode", one.get("crewId"));
                    if (StringUtils.isEmpty(one.get("crewId")) || StringUtils.isEmpty(one.get("getTime")) || StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "运行数据必填项缺失");
                    }
                    QueryWrapper<BasCrew> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code", one.get("crewId"));
                    if (crewService.getOne(queryWrapper) == null) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "crewId错误，无对应机组数据");
                    }
                    String str = JsonUtil.toJson(one);
                    DatCrewData crewData = JsonUtil.fromJson(str, DatCrewData.class);
                    DatCrewDataHistory crewDataHistory = JsonUtil.fromJson(str, DatCrewDataHistory.class);
                    crewData.setUpdateBy(-5);
                    crewDataHistory.setUpdateBy(-5);
                    crewDataList.add(crewData);
                    crewDataHistoryList.add(crewDataHistory);
                }
            }
            crewDataService.saveOrUpdateBatch(crewDataList);
            crewDataHistoryService.saveBatch(crewDataHistoryList);
            r.remove("data");
            return R.ok(r);
        } catch (Exception e) {
            logger.error("receiveCrewDataException", e);
            return R.error(e.getMessage());
        }
    }

    //("上传换热站实时数据 参数为 【heatstationCode(编号)，instantaneousFlow(一次瞬时流量)，cumulativeHeat(一次累计热量),supplyTemp(一次供水温度),backTemp(一次回水温度),supplyPre(一次供压)，backPre（一次回压），getTime（数据时间）】 以上参数转为json 以data为参数名")
    @RequestMapping(value = {"/heat_station_data"}, method = {RequestMethod.POST, RequestMethod.GET})
    public R receiveHeatStationData(HttpServletRequest request, @RequestBody String json) {
        try {
            R r = getParm(request, json);
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<DatHeatstationData> heatstationDataList = new ArrayList<>();
            List<DatHeatstationDataHistory> heatstationDataHistoryArrayList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    one.put("heatstationCode", one.get("heatStationId"));
                    if (StringUtils.isEmpty(one.get("heatStationId")) || StringUtils.isEmpty(one.get("getTime")) || StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "运行数据必填项缺失");
                    }
                    QueryWrapper<BasHeatstation> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code", one.get("heatStationId"));
                    if (heatstationService.getOne(queryWrapper) == null) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "heatStationId错误，无对应热力站数据");
                    }
                    String str = JsonUtil.toJson(one);
                    DatHeatstationData heatstationData = JsonUtil.fromJson(str, DatHeatstationData.class);
                    DatHeatstationDataHistory heatstationDataHistory = JsonUtil.fromJson(str, DatHeatstationDataHistory.class);
                    heatstationData.setUpdateBy(-5);
                    heatstationDataHistory.setUpdateBy(-5);
                    heatstationDataList.add(heatstationData);
                    heatstationDataHistoryArrayList.add(heatstationDataHistory);
                }
            }
            heatstationDataService.saveOrUpdateBatch(heatstationDataList);
            heatstationDataHistoryService.saveBatch(heatstationDataHistoryArrayList);
            r.remove("data");
            return R.ok(r);
        } catch (Exception e) {
            logger.error("receiveHeatStationDataException", e);
            return R.error(e.getMessage());
        }
    }

    //("上传热源出口实时数据 参数为 【heatSourceOutletCode(编号)，instantaneousFlow(瞬时流量)，cumulativeHeat(累计热量),supplyTemp(供水温度),backTemp(回水温度),supplyPre(供压)，backPre（回压），getTime（数据时间）】 以上参数转为json 以data为参数名")
    @RequestMapping(value = {"/heat_source_outlet_data"}, method = {RequestMethod.POST, RequestMethod.GET})
    public R receiveHeatSourceOutletData(HttpServletRequest request, @RequestBody String json) {
        try {
            R r = getParm(request, json);
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<DatHeatSourceOutletData> heatSourceOutletDataList = new ArrayList<>();
            List<DatHeatSourceOutletDataHistory> heatSourceOutletDataHistoryList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    one.put("heatSourceOutletCode", one.get("heatSourceOutletId"));
                    if (StringUtils.isEmpty(one.get("heatSourceOutletId")) || StringUtils.isEmpty(one.get("getTime")) || StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "运行数据必填项缺失");
                    }
                    QueryWrapper<BasHeatsourceExit> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code", one.get("heatSourceOutletId"));
                    if (basHeatsourceExitService.getOne(queryWrapper) == null) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "heatSourceOutletId错误，无对应热力出口数据");
                    }
                    String str = JsonUtil.toJson(one);
                    DatHeatSourceOutletData heatSourceOutletData = JsonUtil.fromJson(str, DatHeatSourceOutletData.class);
                    DatHeatSourceOutletDataHistory heatSourceOutletDataHistory = JsonUtil.fromJson(str, DatHeatSourceOutletDataHistory.class);
                    heatSourceOutletData.setUpdateBy(-5);
                    heatSourceOutletDataHistory.setUpdateBy(-5);
                    heatSourceOutletDataList.add(heatSourceOutletData);
                    heatSourceOutletDataHistoryList.add(heatSourceOutletDataHistory);
                }
            }
            heatSourceOutletDataService.saveOrUpdateBatch(heatSourceOutletDataList);
            heatSourceOutletDataHistoryService.saveBatch(heatSourceOutletDataHistoryList);
            r.remove("data");
            return R.ok(r);
        } catch (Exception e) {
            logger.error("receiveHeatSourceOutletDataException", e);
            return R.error(e.getMessage());
        }
    }

    //("上传住户实时数据 参数为 【householdCode(编号)，cumulativeHeat(累计热量),supplyTemp(供水温度),backTemp(回水温度),roomTemp(室温)，getTime（数据时间）】 以上参数转为json 以data为参数名")
    @RequestMapping(value = {"/house_hold_data"}, method = {RequestMethod.POST, RequestMethod.GET})
    public R receiveHouseHoldData(HttpServletRequest request, @RequestBody String json) {
        try {
            R r = getParm(request, json);
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<DatHouseHoldData> houseHoldDataList = new ArrayList<>();
            List<DatHouseHoldDataHistory> houseHoldDataHistoryList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    one.put("householdCode", one.get("houseHoldId"));
                    if (StringUtils.isEmpty(one.get("houseHoldId")) || StringUtils.isEmpty(one.get("getTime")) || StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "运行数据必填项缺失");
                    }
                    QueryWrapper<BasHousehold> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code", one.get("houseHoldId"));
                    if (householdService.getOne(queryWrapper) == null) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "houseHoldId错误，无对应热用户数据");
                    }
                    String str = JsonUtil.toJson(one);
                    DatHouseHoldData houseHoldData = JsonUtil.fromJson(str, DatHouseHoldData.class);
                    DatHouseHoldDataHistory houseHoldDataHistory = JsonUtil.fromJson(str, DatHouseHoldDataHistory.class);
                    houseHoldDataList.add(houseHoldData);
                    houseHoldDataHistoryList.add(houseHoldDataHistory);
                }
            }

            houseHoldDataService.saveOrUpdateBatch(houseHoldDataList);
            houseHoldDataHistoryService.saveBatch(houseHoldDataHistoryList);
            r.remove("data");
            return r;
        } catch (Exception e) {
            logger.error("receiveHouseHoldDataException", e);
            return R.error(e.getMessage());
        }
    }

    //("上传公建实时数据 参数为 【buildingCode(编号)，instantaneousFlow(瞬时流量),cumulativeHeat(累计热量),supplyTemp(供水温度),backTemp(回水温度)，getTime（数据时间）】 以上参数转为json 以data为参数名")
    @RequestMapping(value = {"/building_data"}, method = {RequestMethod.POST, RequestMethod.GET})
    public R receivePublicBuildingData(HttpServletRequest request, @RequestBody String json) {
        try {
            R r = getParm(request, json);
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<DatPublicBuildingData> publicBuildingDataList = new ArrayList<>();
            List<DatPublicBuildingDataHistory> publicBuildingDataHistoryList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    one.put("buildingCode", one.get("buildingId"));
                    if (StringUtils.isEmpty(one.get("buildingId")) || StringUtils.isEmpty(one.get("getTime")) || StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "运行数据必填项缺失");
                    }
                    QueryWrapper<BasBuilding> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code", one.get("buildingId"));
                    if (basBuildingService.getOne(queryWrapper) == null) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "buildingId错误，无对应热建筑数据");
                    }
                    String str = JsonUtil.toJson(one);
                    DatPublicBuildingData publicBuildingData = JsonUtil.fromJson(str, DatPublicBuildingData.class);
                    DatPublicBuildingDataHistory publicBuildingDataHistory = JsonUtil.fromJson(str, DatPublicBuildingDataHistory.class);
                    publicBuildingDataList.add(publicBuildingData);
                    publicBuildingDataHistoryList.add(publicBuildingDataHistory);
                }
            }

            publicBuildingDataService.saveOrUpdateBatch(publicBuildingDataList);
            publicBuildingDataHistoryService.saveBatch(publicBuildingDataHistoryList);
            r.remove("data");
            return r;
        } catch (Exception e) {
            logger.error("receivePublicBuildingDataException", e);
            return R.error(e.getMessage());
        }
    }

    //("上传居建实时数据 参数为 【buildingCode(编号)，instantaneousFlow(瞬时流量),cumulativeHeat(累计热量),supplyTemp(供水温度),backTemp(回水温度)，getTime（数据时间）】 以上参数转为json 以data为参数名")
    @RequestMapping(value = {"/receiveResidentialBuildingData"}, method = {RequestMethod.POST, RequestMethod.GET})
    public R receiveResidentialBuildingData(HttpServletRequest request, @RequestBody String json) {
        try {
            R r = getParm(request, json);
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<DatResidentialBuildingData> residentialBuildingDataList = new ArrayList<>();
            List<DatResidentialBuildingDataHistory> residentialBuildingDataHistoryList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    one.put("buildingCode", one.get("buildingId"));
                    if (StringUtils.isEmpty(one.get("buildingId")) || StringUtils.isEmpty(one.get("getTime")) || StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "运行数据必填项缺失");
                    }
                    QueryWrapper<BasBuilding> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code", one.get("buildingId"));
                    if (basBuildingService.getOne(queryWrapper) == null) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "buildingId错误，无对应热建筑数据");
                    }
                    String str = JsonUtil.toJson(one);
                    DatResidentialBuildingData residentialBuildingData = JsonUtil.fromJson(str, DatResidentialBuildingData.class);
                    DatResidentialBuildingDataHistory residentialBuildingDataHistory = JsonUtil.fromJson(str, DatResidentialBuildingDataHistory.class);
                    residentialBuildingDataList.add(residentialBuildingData);
                    residentialBuildingDataHistoryList.add(residentialBuildingDataHistory);
                }
            }

            residentialBuildingDataService.saveOrUpdateBatch(residentialBuildingDataList);
            residentialBuildingDataHistoryService.saveBatch(residentialBuildingDataHistoryList);
            r.remove("data");
            return r;
        } catch (Exception e) {
            logger.error("receiveResidentialBuildingDataException", e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 典型测温数据上报
     *
     * @param request
     * @param json
     * @return
     */
    @RequestMapping(value = {"/room_temp"}, method = {RequestMethod.POST})
    public R receiveRoomTemp(HttpServletRequest request, @RequestBody String json) {
        try {
            R r = getParm(request, json);
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<DatRoomtemp> roomtempList = new ArrayList<>();
            List<DatRoomtempHistory> roomtempHistoryList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    one.put("householdCode", one.get("houseHoldId"));
                    if (StringUtils.isEmpty(one.get("houseHoldId")) || StringUtils.isEmpty(one.get("getTime")) || StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "运行数据必填项缺失");
                    }
                    QueryWrapper<BasHousehold> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code", one.get("houseHoldId"));
                    List list1 = householdService.list(queryWrapper);
                    if (list1 == null || list1.size() == 0) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "householdId错误，无对应热用户数据");
                    }
                    String str = JsonUtil.toJson(one);
                    DatRoomtemp roomtemp = JsonUtil.fromJson(str, DatRoomtemp.class);
                    roomtemp.setAddTime(new Date());
                    DatRoomtempHistory roomtempHistory = JsonUtil.fromJson(str, DatRoomtempHistory.class);
                    roomtempHistory.setAddTime(new Date());
                    roomtempList.add(roomtemp);
                    roomtempHistoryList.add(roomtempHistory);
                }
            }
            roomtempService.saveOrUpdateBatch(roomtempList);
            datRoomtempHistoryService.saveBatch(roomtempHistoryList);
            r.remove("data");
            return R.ok(r);
        } catch (Exception e) {
            logger.error("receiveRoomTempException", e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 用户缴费信息上传
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/household_payment"}, method = {RequestMethod.POST})
    public R householdPayment(HttpServletRequest request, @RequestBody String json) {
        R r = getParm(request, json);
        try {
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<HouseholdPayment> householdPaymentList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    one.put("houseHoldCode", one.get("householdId"));
                    one.put("id", one.get("innerId"));
                    if (StringUtils.isEmpty(one.get("householdId")) || StringUtils.isEmpty(one.get("getTime")) || StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "运行数据必填项缺失");
                    }
                    QueryWrapper<BasHousehold> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code", one.get("householdId"));
                    if (householdService.getOne(queryWrapper) == null) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "householdId错误，无对应热用户数据");
                    }
                    String str = JsonUtil.toJson(one);
                    HouseholdPayment payment = JsonUtil.fromJson(str, HouseholdPayment.class);
                    householdPaymentList.add(payment);
                }
            }
            paymentService.saveBatch(householdPaymentList);
            r.remove("data");
            return r;
        } catch (Exception e) {
            logger.error("receiveHouseHoldDataException", e);
            return R.ok(e.getMessage());
        }
    }

    /**
     * 用户退费信息上传
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/household_refund"}, method = {RequestMethod.POST})
    public R householdRefund(HttpServletRequest request, @RequestBody String json) {
        R r = getParm(request, json);
        try {
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<HouseholdRefund> refundList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    one.put("houseHoldCode", one.get("householdId"));
                    one.put("id", one.get("innerId"));
                    if (StringUtils.isEmpty(one.get("householdId")) || StringUtils.isEmpty(one.get("getTime")) || StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "运行数据必填项缺失");
                    }
                    QueryWrapper<BasHousehold> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code", one.get("householdId"));
                    if (householdService.getOne(queryWrapper) == null) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "householdId错误，无对应热用户数据");
                    }
                    String str = JsonUtil.toJson(one);
                    HouseholdRefund refund = JsonUtil.fromJson(str, HouseholdRefund.class);
                    refundList.add(refund);
                }
            }
            refundService.saveBatch(refundList);
            r.remove("data");
            return r;
        } catch (Exception e) {
            logger.error("receiveHouseHoldDataException", e);
            return R.ok(e.getMessage());
        }
    }

    /**
     * 客服数据上传
     *
     * @param request
     * @return
     */
    @RequestMapping("/customer_service")
    public R getCustomerService(HttpServletRequest request, @RequestBody String json) {
        R r = getParm(request, json);
        try {
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<ComplainInfo> complainInfoList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    if (StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "运行数据必填项缺失");
                    }
                    if (StringUtils.isEmpty(one.get("codeCity"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "codeCity缺失");
                    }
                    QueryWrapper<ComplainInfo> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code_city", one.get("codeCity")).eq("company_code", r.get("heatCompanyId"));
                    List<ComplainInfo> complainInfos = complainInfoService.list(queryWrapper);
                    if (complainInfos != null && complainInfos.size() > 0) {
                        logger.info("city_code ========>>>>>>" + one.get("codeCity"));
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "数据重复");
                    }
                    String str = JsonUtil.toJson(one);
                    ComplainInfo complainInfo = JsonUtil.fromJson(str, ComplainInfo.class);
                    QueryWrapper<BasCommunity> communityQueryWrapper = new QueryWrapper<>();
                    communityQueryWrapper.eq("code",complainInfo.getCommunityCode());
                    if (communityService.count(communityQueryWrapper)==0){
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "无此小区数据");
                    }
                    complainInfo.setStatus(1);
                    complainInfo.setComplainLevel(1);
                    complainInfo.setWhoLook("2,3");
                    complainInfo.setCreateTime(new Date());
                    complainInfo.setCompanyCode(r.get("heatCompanyId").toString());
                    complainInfoList.add(complainInfo);
                }
            }
            complainInfoService.saveBatch(complainInfoList);
            r.remove("data");
            return r;
        } catch (Exception e) {
            logger.error("receiveHouseHoldDataException", e);
            return R.ok(e.getMessage());
        }
    }

    @RequestMapping("/service_result")
    public R serviceResult(HttpServletRequest request, @RequestBody String json) {
        R r = getParm(request, json);
        try {
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<ResultInfo> resultInfoList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    if (StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "运行数据必填项缺失");
                    }
                    QueryWrapper<ComplainInfo> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code_city", one.get("codeCity")).eq("company_code", r.get("heatCompanyId"));
                    List<ComplainInfo> complainInfos = complainInfoService.list(queryWrapper);
                    if (complainInfos == null || complainInfos.size() == 0) {
                        logger.info("city_code ========>>>>>>" + one.get("city_code"));
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "投诉数据不存在，无法添加结果数据");
                    }

                    one.put("complainId", complainInfos.get(0).getId());
                    if (!StringUtils.isEmpty(one.get("isOver"))) {//完结则修改状态
                        if (Integer.parseInt(one.get("isOver").toString()) == 1) {
                            ComplainInfo complainInfo = complainInfos.get(0);
                            if (complainInfo.getComplainLevel() == 4) {
                                String accessToken = HttpClientUtil.getAcceccToken();
                                String url = "http://121.28.252.94:10080/DataAPI/ComplaintAPI/UpdateToComplete";
                                Map para = new HashMap();
                                para.put("AccessToken", accessToken);
                                para.put("ComplaintCode", complainInfo.getCodeProvince());
                                para.put("Content", one.get(""));
                                String resultStr = postMap(url, para);
                                Map result = JsonUtil.fromJson(resultStr, Map.class);
                                if (!(boolean) result.get("IsSuccess")) {
                                    return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", result.get("Message").toString());
                                }
                            }
                            complainInfo.setStatus(41);
                            complainInfo.setCloseTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(one.get("overTime").toString()));
                            complainInfoService.updateById(complainInfo);
                        }
                    }
                    String str = JsonUtil.toJson(one);
                    ResultInfo resultInfo = JsonUtil.fromJson(str, ResultInfo.class);
                    resultInfo.setState(1);//投诉等
                    resultInfo.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(one.get("overTime").toString()));
                    resultInfoList.add(resultInfo);
                }
            }
            resultInfoService.saveBatch(resultInfoList);
            r.remove("data");
            return r;
        } catch (Exception e) {
            logger.error("serviceResultException", e);
            return R.ok(e.getMessage());
        }
    }

    /**
     * 日报数据
     *
     * @param request
     * @return
     */
    @RequestMapping("/gather_daily")
    public R gatherTemporary(HttpServletRequest request, @RequestBody String json) {
        R r = getParm(request, json);
        try {
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<GatherTemporary> gatherTemporaryList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    if (StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "必填项缺失");
                    }
                    QueryWrapper<GatherTemporary> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("get_time", one.get("getTime")).eq("company_code", r.get("heatCompanyId"));
                    List<GatherTemporary> myList = gatherTemporaryService.list(queryWrapper);
                    if (myList != null && myList.size() > 0) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "同一天只可上报一次");
                    }
                    String str = JsonUtil.toJson(one);
                    GatherTemporary gatherTemporary = JsonUtil.fromJson(str, GatherTemporary.class);
                    gatherTemporary.setCompanyCode(r.get("heatCompanyId").toString());
                    gatherTemporaryList.add(gatherTemporary);
                }
            }
            gatherTemporaryService.saveBatch(gatherTemporaryList);
            r.remove("data");
            return R.ok(r);
        } catch (Exception e) {
            logger.error("gatherDailyException", e);
            return R.ok(e.getMessage());
        }
    }

    @RequestMapping("/exception_report")
    public R HeatingExceptionReport(HttpServletRequest request, @RequestBody String json) {
        R r = getParm(request, json);
        try {
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<HeatingExceptionInfo> exceptionInfoList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    if (StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "必填项缺失");
                    }
                    if (StringUtils.isEmpty(one.get("codeCity"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "codeCity缺失");
                    }
                    if (StringUtils.isEmpty(one.get("exceptionType"))) {
                        one.put("exceptionType", "故障");
                    }
                    QueryWrapper<HeatingExceptionInfo> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code_city", one.get("codeCity")).eq("company_code", r.get("heatCompanyId"));
                    List<HeatingExceptionInfo> exceptionInfos = heatingExceptionInfoService.list(queryWrapper);
                    if (exceptionInfos != null && exceptionInfos.size() > 0) {
                        logger.info("innerId ========>>>>>>" + one.get("innerId"));
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "数据重复");
                    }
                    String str = JsonUtil.toJson(one);
                    HeatingExceptionInfo exceptionInfo = JsonUtil.fromJson(str, HeatingExceptionInfo.class);
                    exceptionInfo.setCompanyCode(r.get("heatCompanyId").toString());
                    exceptionInfo.setComplainLevel(1);
                    exceptionInfo.setCreateTime(new Date());
                    exceptionInfo.setSource(4);
                    exceptionInfoList.add(exceptionInfo);
                }
            }
            heatingExceptionInfoService.saveBatch(exceptionInfoList);
            r.remove("data");
            return r;
        } catch (Exception e) {
            logger.error("gatherDailyException", e);
            return R.ok(e.getMessage());
        }
    }

    @RequestMapping("/exception_result")
    public R exceptionResult(HttpServletRequest request, @RequestBody String json) {
        R r = getParm(request, json);
        try {
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<ResultInfo> resultInfoList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    if (StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "运行数据必填项缺失");
                    }
                    QueryWrapper<HeatingExceptionInfo> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code_city", one.get("codeCity")).eq("company_code", r.get("heatCompanyId"));
                    List<HeatingExceptionInfo> exceptionInfos = heatingExceptionInfoService.list(queryWrapper);
                    if (exceptionInfos == null || exceptionInfos.size() == 0) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "投诉数据不存在，无法添加结果数据");
                    }
                    if (!StringUtils.isEmpty(one.get("isOver"))) {//完结则修改状态
                        if (Integer.parseInt(one.get("isOver").toString()) == 1) {
                            HeatingExceptionInfo exceptionInfo = exceptionInfos.get(0);
                            exceptionInfo.setCloseTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(one.get("overTime").toString()));
                            exceptionInfo.setStatus(1);
                            heatingExceptionInfoService.updateById(exceptionInfo);
                        }
                    }

                    one.put("complainId", exceptionInfos.get(0).getId());
                    String str = JsonUtil.toJson(one);
                    ResultInfo resultInfo = JsonUtil.fromJson(str, ResultInfo.class);
                    resultInfo.setResultCodeCity("rs" + System.currentTimeMillis());
                    resultInfo.setState(2);//供暖异常
                    resultInfo.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(one.get("overTime").toString()));
                    resultInfoList.add(resultInfo);
                }
            }
            resultInfoService.saveBatch(resultInfoList);
            r.remove("data");
            return R.ok(r);
        } catch (Exception e) {
            logger.error("exceptionResultException", e);
            return R.ok(e.getMessage());
        }
    }

    @RequestMapping("/poly_line")
    public R MapPolyLine(HttpServletRequest request, @RequestBody String json) {
        R r = getParm(request, json);
        try {
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<MapPolylinevalue> polylinevalueList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    if (StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "运行数据必填项缺失");
                    }
                    if (!StringUtils.isEmpty(one.get("lineId"))) {
                        QueryWrapper<MapPolylinevalue> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("id", one.get("lineId")).eq("heatcompany_code", r.get("heatCompanyId"));
                        List<MapPolylinevalue> getList = mapPolylinevalueService.list(queryWrapper);
                        if (getList == null) {
                            return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "lineId与heatCompanyId不匹配");
                        }
                        one.put("id", one.get("lineId"));
                    }
                    if (StringUtils.isEmpty(one.get("line"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "line不可为空");
                    }

                    String regx = "^\\[(\\[(\\d*)\\.(\\d*),(\\d*)\\.(\\d*)\\],)*\\[(\\d*)\\.(\\d*),(\\d*)\\.(\\d*)\\]\\]$";
                    String line = one.get("line").toString();
                    if (!line.matches(regx)) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "line坐标格式不正确");
                    }
                    one.put("mapx", one.get("line"));
                    one.put("heatcompanyCode", r.get("heatCompanyId").toString());
                    String str = JsonUtil.toJson(one);
                    MapPolylinevalue polylinevalue = JsonUtil.fromJson(str, MapPolylinevalue.class);
                    polylinevalueList.add(polylinevalue);
                }
            }
            mapPolylinevalueService.saveOrUpdateBatch(polylinevalueList);
            System.out.println("=========>>>>>" + JsonUtil.toJson(polylinevalueList));
            r.put("data", polylinevalueList);
            return R.ok(r);
        } catch (Exception e) {
            logger.error("exceptionResultException", e);
            return R.ok(e.getMessage());
        }
    }


    //下发投诉转办单
    @RequestMapping("/pull_service")
    public R pullService(HttpServletRequest request, @RequestBody String json) {
        Map map = JsonUtil.fromJson(json, Map.class);
        if (StringUtils.isEmpty(map.get("requestId"))) {
            return R.ok("", "4", "requestId为空");
        }
        String requestId = map.get("requestId").toString();
        if (StringUtils.isEmpty(map.get("heatCompanyId"))) {
            return R.ok(requestId, "", "4", "heatCompanyId为空");
        }
        String heatCompanyId = map.get("heatCompanyId").toString();
        QueryWrapper<BasHeatcompany> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", heatCompanyId);
        BasHeatcompany basHeatcompany = heatcompanyServicel.getOne(queryWrapper);
        if (basHeatcompany == null) {
            return R.ok(requestId, heatCompanyId, "4", "供热企业代码不正确");
        }
        if (StringUtils.isEmpty(map.get("startTime")) || StringUtils.isEmpty(map.get("endTime"))) {
            return R.ok(requestId, heatCompanyId, "4", "起止时间不准为空");
        }
        try {
            QueryWrapper<ComplainInfo> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.select("code_city as codeCity", "house_holder as houseHolder", "region_code as regionCode", "community_code as communityCode", "company_code as companyCode", "address", "telephone"
                    , "complain_type as complainType", "handle_time as handleTime", "problem_description as problemDescription", "complaint_note as complaintNote", "community_name as communityName", "is_oversee as isOversee");

            queryWrapper1.eq("company_code", map.get("heatCompanyId"))
                    .and(wrapper -> wrapper.eq("status", 2).or().eq("is_oversee", "1"))
                    .ge("create_time", map.get("startTime")).le("create_time", map.get("endTime"));


            /*queryWrapper1.eq("company_code", map.get("heatCompanyId")).eq("is_complaint", 1).ne("complain_level", 1)
                    .ge("create_time", map.get("startTime")).le("create_time", map.get("endTime")).eq("status", 1);*/
            List<Map<String, Object>> complainInfoList = complainInfoService.listMaps(queryWrapper1);
            return R.ok(requestId, heatCompanyId, "0", "查询成功", complainInfoList);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("联系开发人员");
        }
    }

    //下发供暖系统异常转办单
    @RequestMapping("/pull_exception")
    public R pullException(HttpServletRequest request, @RequestBody String json) {
        Map map = JsonUtil.fromJson(json, Map.class);
        if (StringUtils.isEmpty(map.get("requestId"))) {
            return R.ok("", "4", "requestId为空");
        }
        String requestId = map.get("requestId").toString();
        if (StringUtils.isEmpty(map.get("heatCompanyId"))) {
            return R.ok(requestId, "", "4", "heatCompanyId为空");
        }
        String heatCompanyId = map.get("heatCompanyId").toString();
        QueryWrapper<BasHeatcompany> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", heatCompanyId);
        BasHeatcompany basHeatcompany = heatcompanyServicel.getOne(queryWrapper);
        if (basHeatcompany == null) {
            return R.ok(requestId, heatCompanyId, "4", "供热企业代码不正确");
        }
        if (StringUtils.isEmpty(map.get("startTime")) || StringUtils.isEmpty(map.get("endTime"))) {
            return R.ok(requestId, heatCompanyId, "4", "起止时间不准为空");
        }
        try {
            QueryWrapper<HeatingExceptionInfo> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.select("start_time as startTime", "code_city codeCity", "region_code as regionCode", "company_code as companyCode",
                    "exception_type as exceptionType", "address", "case_description as caseDescription", "disposal_description as disposalDescription", "contact", "telephone", "impact_area as impactArea",
                    "impact_house_count as impactHouseCount", "impact_time as impactTime", "plan_reply_time as planReplyTime", "is_complaint as isComplaint", "is_oversee as isOversee");

            queryWrapper1.eq("company_code", map.get("heatCompanyId"))
                    .and(wrapper -> wrapper.eq("is_complaint", 1).ne("complain_level", 1).or().eq("is_oversee", "1"))
                    .eq("status", 0).ge("start_time", map.get("startTime")).le("start_time", map.get("endTime"));

//            queryWrapper1.eq("company_code", map.get("heatCompanyId")).eq("is_complaint", 1).ne("complain_level", 1)
//                    .ge("start_time", map.get("startTime")).le("start_time", map.get("endTime")).eq("status", 0);
            List<Map<String, Object>> complainInfoList = heatingExceptionInfoService.listMaps(queryWrapper1);
            return R.ok(requestId, heatCompanyId, "0", "查询成功", complainInfoList);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("联系开发人员");
        }
    }


    /**
     * 下发投诉驳回
     * 根据驳回时间查询
     */

    @RequestMapping("/pull_reject_service")
    public R pullRejectService(HttpServletRequest request, @RequestBody String json) {
        Map map = JsonUtil.fromJson(json, Map.class);
        if (StringUtils.isEmpty(map.get("requestId"))) {
            return R.ok("", "4", "requestId为空");
        }
        String requestId = map.get("requestId").toString();
        if (StringUtils.isEmpty(map.get("heatCompanyId"))) {
            return R.ok(requestId, "", "4", "heatCompanyId为空");
        }
        String heatCompanyId = map.get("heatCompanyId").toString();
        QueryWrapper<BasHeatcompany> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", heatCompanyId);
        BasHeatcompany basHeatcompany = heatcompanyServicel.getOne(queryWrapper);
        if (basHeatcompany == null) {
            return R.ok(requestId, heatCompanyId, "4", "供热企业代码不正确");
        }
        if (StringUtils.isEmpty(map.get("startTime")) || StringUtils.isEmpty(map.get("endTime"))) {
            return R.ok(requestId, heatCompanyId, "4", "起止时间不准为空");
        }
        try {
            QueryWrapper<ComplainInfo> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.select("code_city as codeCity", "house_holder as houseHolder", "region_code as regionCode", "community_code as communityCode", "company_code as companyCode", "address", "telephone"
                    , "complain_type as complainType", "handle_time as handleTime", "problem_description as problemDescription", "complaint_note as complaintNote", "community_name as communityName", "inner_id as innerId", "update_time as rejectTime");

            queryWrapper1.eq("company_code", map.get("heatCompanyId")).eq("complain_level", 1).eq("source", 4)
                    .eq("status_county", -1).ge("update_time", map.get("startTime")).le("update_time", map.get("endTime"));
                    /*.and(wrapper -> wrapper.eq("is_complaint", 1).ne("complain_level", 1).or().eq("is_oversee", "1"))
                    .eq("status", 1).ge("create_time", map.get("startTime")).le("create_time", map.get("endTime"));*/

            List<Map<String, Object>> complainInfoList = complainInfoService.listMaps(queryWrapper1);
            return R.ok(requestId, heatCompanyId, "0", "查询成功", complainInfoList);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("联系开发人员");
        }
    }

    /**
     * 驳回客服数据更新
     *
     * @param request
     * @return
     */
    /*@RequestMapping("/reject_customer_service_update")
    public R getRejectCustomerService(HttpServletRequest request, @RequestBody String json) {
        R r = getParm(request, json);
        try {
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<ComplainInfo> complainInfoList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    if (StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "运行数据必填项缺失");
                    }
                    if (StringUtils.isEmpty(one.get("codeCity"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "codeCity缺失");
                    }
                    QueryWrapper<ComplainInfo> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code_city", one.get("codeCity")).eq("company_code", r.get("heatCompanyId"));
                    List<ComplainInfo> complainInfos = complainInfoService.list(queryWrapper);
                    if (complainInfos != null && complainInfos.size() > 0) {
                        if (complainInfos.get(0).getStatusCounty() == -1) {
                            String str = JsonUtil.toJson(one);
                            ComplainInfo complainInfo = JsonUtil.fromJson(str, ComplainInfo.class);
                            complainInfo.setId(complainInfos.get(0).getId());
                            complainInfo.setSource(4);
                            complainInfo.setComplainLevel(1);
                            //重置审核状态
                            complainInfo.setStatusCity(0);
                            complainInfo.setStatusCounty(0);
                            complainInfo.setCompanyCode(r.get("heatCompanyId").toString());
                            complainInfoList.add(complainInfo);
                        } else {
                            return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "该客服数据非驳回数据，不可更改");
                        }
                    } else {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "客服数据不存在，请检查编码");
                    }


                }
            }
            complainInfoService.updateBatchById(complainInfoList);
            r.remove("data");
            return r;
        } catch (Exception e) {
            logger.error("receiveHouseHoldDataException", e);
            return R.ok(e.getMessage());
        }
    }
*/
    //下发供暖系统异常驳回数据
    @RequestMapping("/pull_reject_exception")
    public R pullRejectException(HttpServletRequest request, @RequestBody String json) {
        Map map = JsonUtil.fromJson(json, Map.class);
        if (StringUtils.isEmpty(map.get("requestId"))) {
            return R.ok("", "4", "requestId为空");
        }
        String requestId = map.get("requestId").toString();
        if (StringUtils.isEmpty(map.get("heatCompanyId"))) {
            return R.ok(requestId, "", "4", "heatCompanyId为空");
        }
        String heatCompanyId = map.get("heatCompanyId").toString();
        QueryWrapper<BasHeatcompany> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", heatCompanyId);
        BasHeatcompany basHeatcompany = heatcompanyServicel.getOne(queryWrapper);
        if (basHeatcompany == null) {
            return R.ok(requestId, heatCompanyId, "4", "供热企业代码不正确");
        }
        if (StringUtils.isEmpty(map.get("startTime")) || StringUtils.isEmpty(map.get("endTime"))) {
            return R.ok(requestId, heatCompanyId, "4", "起止时间不准为空");
        }
        try {
            QueryWrapper<HeatingExceptionInfo> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.select("start_time as startTime", "code_city codeCity", "region_code as regionCode", "company_code as companyCode",
                    "exception_type as exceptionType", "address", "case_description as caseDescription", "disposal_description as disposalDescription", "contact", "telephone", "impact_area as impactArea",
                    "impact_house_count as impactHouseCount", "impact_time as impactTime", "plan_reply_time as planReplyTime", "inner_id as innerId", "update_time as rejectTime");

            queryWrapper1.eq("company_code", map.get("heatCompanyId")).eq("complain_level", 1).eq("source", 4)
                    .eq("status_county", -1).ge("update_time", map.get("startTime")).le("update_time", map.get("endTime"));
//                    .and(wrapper -> wrapper.eq("is_complaint", 1).ne("complain_level", 1).or().eq("is_oversee", "1"))
//                    .eq("status", 0).ge("start_time", map.get("startTime")).le("start_time", map.get("endTime"));

            List<Map<String, Object>> complainInfoList = heatingExceptionInfoService.listMaps(queryWrapper1);
            return R.ok(requestId, heatCompanyId, "0", "查询成功", complainInfoList);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("联系开发人员");
        }
    }

    /**
     * 驳回供暖异常信息更新
     *
     * @param request
     * @param json
     * @return
     */
    @RequestMapping("/reject_exception_update")
    public R HeatingExceptionUpdate(HttpServletRequest request, @RequestBody String json) {
        R r = getParm(request, json);
        try {
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<HeatingExceptionInfo> exceptionInfoList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    if (StringUtils.isEmpty(one.get("innerId"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "必填项缺失");
                    }
                    if (StringUtils.isEmpty(one.get("codeCity"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "codeCity缺失");
                    }
                    QueryWrapper<HeatingExceptionInfo> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code_city", one.get("codeCity")).eq("company_code", r.get("heatCompanyId"));
                    List<HeatingExceptionInfo> exceptionInfos = heatingExceptionInfoService.list(queryWrapper);
                    if (exceptionInfos != null && exceptionInfos.size() > 0) {
                        if (exceptionInfos.get(0).getStatusCounty() == -1) {
                            String str = JsonUtil.toJson(one);
                            HeatingExceptionInfo exceptionInfo = JsonUtil.fromJson(str, HeatingExceptionInfo.class);
                            exceptionInfo.setId(exceptionInfos.get(0).getId());
                            exceptionInfo.setCompanyCode(r.get("heatCompanyId").toString());
                            exceptionInfo.setComplainLevel(1);
                            exceptionInfo.setStatusCity(0);
                            exceptionInfo.setStatusCounty(0);
                            exceptionInfo.setSource(4);
                            exceptionInfoList.add(exceptionInfo);
                        } else {
                            return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "该供暖异常数据非驳回数据，不可更改");
                        }
                    } else {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "供热异常数据不存在，请检查编码");
                    }

                }
            }
            heatingExceptionInfoService.updateBatchById(exceptionInfoList);
            r.remove("data");
            return r;
        } catch (Exception e) {
            logger.error("gatherDailyException", e);
            return R.ok(e.getMessage());
        }
    }

    /**
     * 获取驳回日报数据
     *
     * @param request
     * @param json
     * @return
     */
    @RequestMapping("/reject_gather_daily")
    public R getRejectGatherDaily(HttpServletRequest request, @RequestBody String json) {
        try {
            Map map = JsonUtil.fromJson(json, Map.class);
            if (StringUtils.isEmpty(map.get("requestId"))) {
                return R.ok("", "4", "requestId为空");
            }
            String requestId = map.get("requestId").toString();
            if (StringUtils.isEmpty(map.get("heatCompanyId"))) {
                return R.ok(requestId, "", "4", "heatCompanyId为空");
            }
            String heatCompanyId = map.get("heatCompanyId").toString();
            QueryWrapper<BasHeatcompany> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code", heatCompanyId);
            BasHeatcompany basHeatcompany = heatcompanyServicel.getOne(queryWrapper);
            if (basHeatcompany == null) {
                return R.ok(requestId, heatCompanyId, "4", "供热企业代码不正确");
            }
            if (StringUtils.isEmpty(map.get("startTime"))) {
                return R.ok(requestId, heatCompanyId, "4", "时间不准为空");
            }
            QueryWrapper<GatherTemporary> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.select("company_code as companyCode", "complain_now as complainNow", "complain_over as complainOver", "consult_now as consultNow", "consult_over as consultOver", "service_now as serviceNow", "service_over as serviceOver", "DATE_FORMAT(get_time,'%Y-%m-%d') as getTime");
            queryWrapper1.ge("update_time", map.get("startTime") + " 00:00:00").le("update_time", map.get("startTime") + " 23:59:59")
                    .eq("company_code", heatCompanyId).eq("status_county", -1);
            List<GatherTemporary> list = gatherTemporaryService.list(queryWrapper1);
            if (list.size()>1){
                return R.ok(requestId, heatCompanyId, "4", "只可拉取一天日报数据");
            }
            return R.ok(requestId, heatCompanyId, "0", "查询成功", list);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return R.ok(e.getMessage());
        }
    }

    /**
     * 驳回日报数据更新
     *
     * @param request
     * @param json
     * @return
     */
    @RequestMapping(value = "/reject_gather_daily_update", method = RequestMethod.POST)
    public R rejectGatherDailyUpdate(HttpServletRequest request, @RequestBody String json) {
        R r = getParm(request, json);
        try {
            if (Integer.parseInt(r.get("responseCode").toString()) != 0) {
                return r;
            }
            List<Map> list = (ArrayList<Map>) r.get("data");
            List<GatherTemporary> temporaryList = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Map one = list.get(i);
                    if (StringUtils.isEmpty(one.get("getTime"))) {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "必填项缺失");
                    }
                    QueryWrapper<GatherTemporary> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("get_time", one.get("getTime")).eq("company_code", r.get("heatCompanyId"));
                    List<GatherTemporary> temporaries = gatherTemporaryService.list(queryWrapper);
                    if (temporaries != null && temporaries.size() > 0) {
                        if (temporaries.get(0).getStatusCounty() == -1) {
                            String str = JsonUtil.toJson(one);
                            GatherTemporary gatherTemporary = JsonUtil.fromJson(str, GatherTemporary.class);
                            gatherTemporary.setId(temporaries.get(0).getId());
                            gatherTemporary.setCompanyCode(r.get("heatCompanyId").toString());
                            gatherTemporary.setStatusCity(0);
                            gatherTemporary.setStatusCounty(0);
                            gatherTemporary.setSource(1);
                            temporaryList.add(gatherTemporary);
                        } else {
                            return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "该供暖异常数据非驳回数据，不可更改");
                        }
                    } else {
                        return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "供热异常数据不存在，请检查编码");
                    }

                }
            } else {
                return R.ok(r.get("requestId").toString(), r.get("heatCompanyId").toString(), "4", "无请求数据");
            }
            gatherTemporaryService.updateBatchById(temporaryList);
            r.remove("data");
            return r;
        } catch (Exception e) {
            logger.error("gatherDailyException", e);
            return R.ok(e.getMessage());
        }
    }

    public LocalDateTime UDateToLocalDateTime(String time) {
        LocalDateTime localDateTime = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = format.parse(time);
            Instant instant = date.toInstant();
            ZoneId zone = ZoneId.systemDefault();
            localDateTime = LocalDateTime.ofInstant(instant, zone);
        } catch (Exception e) {

        }
        return localDateTime;
    }

    public static void main(String[] args) {
        Map para = new HashMap();
        para.put("get_token", "12345dgfdf1gg44");
        para.put("requestId", "123");
        para.put("heatCompanyId", "130973022");
        para.put("appId", "YtFpn3R2SlEyhFUf");
        para.put("appSecert", "T4bm3xGJMJBgQyiSlAtsq83gzVIyfgvr");
        String a = HttpClientUtil.postJson("http://127.0.0.1:31080/Api/get_token", JsonUtil.toJson(para));
        System.out.println(a);
//        String regx = "^\\[(\\[(\\d*)\\.(\\d*),(\\d*)\\.(\\d*)\\],)*\\[(\\d*)\\.(\\d*),(\\d*)\\.(\\d*)\\]\\]$";
//        String line = "[[116.547174,38.065281],[116.547174,38.065281]]";
//        System.out.println(line.matches(regx));

    }
}
